import React, { useEffect } from "react";
import { Modal, Form, Input, InputNumber, message, Button } from "antd";

const UserModel = ({
  showModel,
  handleOk,
  handleCancel,
  initialData = null,
}) => {
  // 获取Form实例，用于表单控制和验证
  const [form] = Form.useForm();

  // 初始化表单值（编辑/新增场景）
  useEffect(() => {
    if (showModel) {
      form.setFieldsValue(
        initialData
          ? {
              name: initialData.name || "",
              email: initialData.email || "",
              age: initialData.age || null,
            }
          : {
              name: "",
              email: "",
              age: null,
            }
      );
    }
  }, [showModel, initialData, form]);

  // 提交表单（包含验证）
  const handleSubmit = async () => {
    try {
      // 触发表单验证，验证通过后返回表单值
      const values = await form.validateFields();
      handleOk(values); // 传给父组件
      message.success("验证通过，提交成功");
    } catch (errorInfo) {
      // 验证失败时的处理
      console.log("表单验证失败：", errorInfo);
      message.error("请完善表单信息");
    }
  };

  return (
    <Modal
      title={
        initialData?.type === "edit"
          ? "编辑用户"
          : initialData?.type === "view"
          ? "查看详情"
          : "新增用户"
      }
      open={showModel}
      onOk={handleSubmit}
      onCancel={handleCancel}
      width={600}
      // 根据不同模式动态生成底部按钮
      footer={
        initialData?.type === "view"
          ? [
              // 查看模式：只显示关闭按钮
              <Button key="close" onClick={handleCancel}>
                关闭
              </Button>,
            ]
          : [
              // 编辑/新增模式：显示取消和确定按钮
              <Button key="cancel" onClick={handleCancel}>
                取消
              </Button>,
              <Button key="submit" type="primary" onClick={handleSubmit}>
                {initialData?.type === "edit" ? "保存" : "新增"}
              </Button>,
            ]
      }
    >
      <Form form={form} layout="inline" style={{ marginTop: 16, gap: 16 }}>
        {/* 姓名字段验证：必填 */}
        <Form.Item
          name="name"
          label="姓名"
          rules={[
            { required: true, message: "请输入姓名" },
            { min: 2, message: "姓名长度不能少于2个字符" },
            { max: 10, message: "姓名长度不能超过10个字符" },
          ]}
        >
          <Input
            placeholder="请输入姓名"
            style={{ width: 190 }}
            disabled={initialData?.type === "view"}
          />
        </Form.Item>

        {/* 年龄字段验证：必填 + 范围限制 */}
        <Form.Item
          name="age"
          label="年龄"
          rules={[
            { required: true, message: "请输入年龄" },
            // { type: 'number', message: '年龄必须是数字' },
            // { min: 0, message: '年龄不能小于0' },
            // { max: 150, message: '年龄不能大于150' },
            {
              type: "number",
              min: 0,
              max: 150,
              message: "年龄必须在0-150之间",
            },
          ]}
        >
          <InputNumber
            placeholder="请输入年龄"
            style={{ width: 190 }}
            disabled={initialData?.type === "view"}
          />
        </Form.Item>

        {/* 邮箱字段验证：必填 + 格式验证 */}
        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            { required: true, message: "请输入邮箱" },
            { type: "email", message: "请输入正确的邮箱格式" },
          ]}
        >
          <Input
            placeholder="请输入邮箱"
            type="email"
            style={{ width: 190 }}
            disabled={initialData?.type === "view"}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UserModel;
